// Author: wsfuyibing <682805@qq.com>
// Date: 2025-05-15

package add

import (
	"context"
	"fmt"
	"gitee.com/go-libs/db-xorm/db"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/errs"
	"server/app/http/logics/master/shop/goods"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/kind"
	"server/app/lib"
	"strings"
)

// Logic
// 添加商品.
type Logic struct {
	goods.Logic

	admin  *models.ArcadeAdmins
	arcade *models.Arcades

	affects     int64
	category    *models.GoodsCategory
	goods       *models.Goods
	kind        kind.ArcadeAdminOperation
	kindContent string
	purchase    *models.GoodsPurchase

	request  *Request
	response *Response
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: &Response{},
	}
}

// After
// 后置日志.
func (o *Logic) After(ctx context.Context, _ iris.Context, _ result.Result) {
	if o.affects > 0 {
		_, _ = services.NewArcadeLogsService().Add(ctx,
			o.arcade, o.admin, o.kind, o.kindContent,
		)
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	if err = validator.Json(i, o.request); err == nil {
		o.arcade, o.admin = lib.Arcade.GetMaster().GetArcade(i)
	}
	return
}

// Run
// 执行逻辑.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		err error
		res = result.New()
	)
	// 1. 事务处理.
	if err = db.Transaction(ctx,
		o.RunCheckCategory,
		o.RunSave,
		o.RunSavePurchase,
		o.RunSaveSync,
		o.RunFinance,
		o.RunStatistic,
	); err != nil {
		return res.WithError(err)
	}
	// 2. 保存完成.
	o.response.Id = o.goods.Id
	o.response.Name = o.goods.Name
	return res.With(o.response)
}

// RunCheckCategory
// 校验类别.
func (o *Logic) RunCheckCategory(ctx context.Context, sess *db.Session) (err error) {
	var has bool
	if o.request.CategoryId > 0 {
		if o.category, has, err = services.NewGoodsCategoryService(sess).Dao.GetById(ctx, o.request.CategoryId); err != nil {
			err = errs.ErrDatabaseQuery
		} else if !has || o.category.ArcadeId != o.arcade.Id {
			err = errs.ErrGoodsCategoryNotFound
		}
	}
	return
}

// RunSave
// 创建商品.
func (o *Logic) RunSave(ctx context.Context, sess *db.Session) (err error) {
	if o.goods, err = services.NewGoodsService(sess).Dao.AddByStruct(ctx, &models.Goods{
		ArcadeId:   o.arcade.Id,
		Deleted:    kind.DeletedNo,
		CategoryId: o.request.CategoryId,
		Unit:       o.request.Unit,
		State:      kind.GoodsStateDisabled,
		Stock:      o.request.PurchaseCount,
		SalePrice:  o.request.SalePrice,
		Name:       o.request.Name,
		Image:      o.request.Image,
	}); err != nil {
		err = errs.ErrDatabaseQuery
	}
	return
}

// RunSavePurchase
// 创建库存.
func (o *Logic) RunSavePurchase(ctx context.Context, sess *db.Session) (err error) {
	if o.purchase, err = services.NewGoodsPurchaseService(sess).Dao.AddByStruct(ctx, &models.GoodsPurchase{
		ArcadeId:      o.arcade.Id,
		GoodsId:       o.goods.Id,
		PurchasePrice: o.request.PurchasePrice,
		PurchaseCost:  o.request.PurchaseCost,
		PurchaseCount: o.request.PurchaseCount,
	}); err != nil {
		err = errs.ErrDatabaseQuery
	}
	return
}

// RunSaveSync
// 库存绑定.
func (o *Logic) RunSaveSync(ctx context.Context, sess *db.Session) (err error) {
	if _, err = services.NewGoodsService(sess).Dao.UpdateFieldsById(ctx, map[string]any{
		"deleted":     kind.DeletedNo,
		"purchase_id": o.purchase.Id,
	}, o.goods.Id); err != nil {
		err = errs.ErrDatabaseQuery
		return
	}

	if _, err = services.NewGoodsPurchaseService(sess).Dao.UpdateFieldsById(ctx, map[string]any{
		"deleted": kind.DeletedNo,
	}, o.purchase.Id); err != nil {
		err = errs.ErrDatabaseQuery
		return
	}

	o.RunSaveLog()
	return
}

// RunFinance
// 处理财务.
func (o *Logic) RunFinance(ctx context.Context, sess *db.Session) (err error) {
	err = o.BuildFinanceRecords(ctx, sess, o.arcade, o.admin, o.goods, o.purchase)
	return
}

// RunSaveLog
// 编辑分类日志.
func (o *Logic) RunSaveLog() {
	var changes = []string{
		fmt.Sprintf(`商品[%s]`, o.request.Name),
		fmt.Sprintf(`单位[%s]`, o.request.Unit.Text()),
		fmt.Sprintf(`售价[%v]`, o.request.SalePrice),
		fmt.Sprintf(`库存[%v]`, o.request.PurchaseCount),
	}

	o.kind = kind.ArcadeAdminOperationShopGoodsCreate
	o.kindContent = o.kind.ToShopGoodsCreate(strings.Join(changes, ", "))
}

// RunStatistic
// 重建统计.
func (o *Logic) RunStatistic(ctx context.Context, sess *db.Session) (err error) {
	if o.response.ShopTotal, err = o.CalcTotal(sess, o.arcade.Id); err == nil {
		if o.response.ShopCount, err = o.CalcForSale(sess, o.arcade.Id); err == nil {
			if err = o.CalcUpdate(sess, o.arcade.Id, o.response.ShopTotal, o.response.ShopCount); err == nil {
				err = o.CalcCategory(ctx, sess, o.arcade.Id)
			}
		}
	}
	return
}
